package com.easy.carl.algorithm.array.matrix;

import java.util.Arrays;

/**
 * @ClassName GenerateMatrix59
 * @Description 59. 螺旋矩阵 II
 * @Author zheng
 * @Date 2021/12/16 9:43
 * @Version 1.0
 **/
public class GenerateMatrix59 {
    public int[][] generateMatrix(int n) {
        //结果
        int[][] res = new int[n][n];
        //当前填充值
        int current = 1;
        //边长为n的正方形，全部填充完毕需要的圈数
        int loop = n / 2;
        //每旋转一圈后，n的偏移量
        int offset = 1;
        //行
        int row = 0;
        //列
        int col = 0;
        while (loop > 0) {
            int tmpRow = row;
            int tmpCol = col;
            //横向 从左至右 左闭右开 ,列递增
            for (; tmpCol < n - offset; tmpCol++) {
                res[tmpRow][tmpCol] = current;
                current++;
            }
            //竖向 从上到下 上闭下开
            for (; tmpRow < n - offset; tmpRow++) {
                res[tmpRow][tmpCol] = current;
                current++;
            }
            //横向 从右至左 右闭左开
            for (; tmpCol >= offset; tmpCol--) {
                res[tmpRow][tmpCol] = current++;
            }
            //竖向 从下至上 下闭上开
            for (; tmpRow >= offset; tmpRow--) {
                res[tmpRow][tmpCol] = current++;
            }
            loop--;
            row++;
            col++;
            offset++;
        }
        if (n % 2 != 0) {
            res[row][row] = current;
        }
        return res;
    }

    public static void main(String[] args) {
        GenerateMatrix59 generateMatrix59 = new GenerateMatrix59();
        System.out.println(Arrays.deepToString(generateMatrix59.generateMatrix(5)));
    }
}
